package com.dmall.chapter06.section05;

public class LeetCode733 {

    private int R, C;
    private boolean[][] visited;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private int color;
    private int newColor;

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        R = image.length;
        if (R == 0) {
            return image;
        }
        C = image[0].length;
        if (C == 0) {
            return image;
        }
        color = image[sr][sc];
        this.newColor = newColor;
        visited = new boolean[R][C];
        dfs(image, sr, sc);
        return image;
    }

    private void dfs(int[][] image, int x, int y) {
        visited[x][y] = true;
        image[x][y] = newColor;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0];
            int nexty = y + dirs[i][1];
            if (inArea(nextx, nexty) && !visited[nextx][nexty] && image[nextx][nexty] == color) {
                dfs(image, nextx, nexty);
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        int[][] image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
        LeetCode733 leetCode733 = new LeetCode733();
        int[][] newImage = leetCode733.floodFill(image, 1, 1, 2);
        for (int[] chars : newImage) {
            for (int c : chars) {
                System.out.print(c + " ");
            }
            System.out.println();
        }
    }
}
